package ca.uwindsor.cs.deepweb.estimation.method.border;

import java.util.HashMap;
import java.util.Set;

public class MatrixDEV {

	protected String Field;

	protected final String[] terms;

	protected int[][] term_docslist;

	protected HashMap<String,Integer> docid_index;
	
	protected int[] inverseDocumentWeight;

	protected float[] QueryWeight;

	protected int index;

	protected int p;

	/**
	 * @param FieldName
	 * @param wordlist
	 */
	public MatrixDEV(String FieldName, String[] wordlist) {
		int initialCapacity = wordlist.length;
		terms = wordlist;
		term_docslist = new int[initialCapacity][];
		docid_index = new HashMap<String,Integer>(initialCapacity * 100);
		Field = FieldName;
		QueryWeight = new float[initialCapacity];
	}

	/**
	 * @param i
	 * @param documents
	 */
	public void addQuery(int i, Set<String> documents) {

		int[] array = null;
		if (documents.size() != 0) {
			array = new int[documents.size()];
			index = 0;
			// add new documents to unique id list
			for (String s : documents) {
				if (!docid_index.containsKey(s)) {
					p = docid_index.size();
					docid_index.put(s, p);
				} else {
					p = docid_index.get(s).intValue();
				}
				array[index] = p;
				index++;
			}
		}
		// add to term-docs list
		term_docslist[i] = array;
	}

	/**
	 * 
	 */
	public void calculateInverseDocumentWeight() {
		inverseDocumentWeight = new int[docid_index.size()];
		for (int[] l : term_docslist) {
			if (l != null) {
				for (int i : l) {
					inverseDocumentWeight[i]++;
				}
			}
		}
	}

	/**
	 * 
	 */
	public void calculateQueryWeight() {
		int[] l;
		float weight;
		for (index = 0; index < terms.length; index++) {
			l = term_docslist[index];
			weight = 0;
			if (l != null) {
				for (int i : l) {
					weight += 1 / (float) inverseDocumentWeight[i];
				}
			}
			QueryWeight[index] = weight;
		}
	}

	/**
	 * @param i
	 * @return the document frequency of a term
	 */
	public int getDocumentFrequencybyTerm(int i) {
		if (term_docslist[i] == null) {
			return 0;
		} else {
			return term_docslist[i].length;
		}
	}

	/**
	 * @return the documentWeight
	 */
	public int[] getInverseDocumentWeight() {
		return inverseDocumentWeight;
	}

	/**
	 * @return the queryWeight
	 */
	public float[] getQueryWeight() {
		return QueryWeight;
	}

	/**
	 * @return the mean weight of queries
	 */
	public float getMeanQueryWeight() {
		float mean = 0;
		float sum = 0;
		for (float f : QueryWeight) {
			sum += f;
		}
		mean = sum / QueryWeight.length;
		return mean;
	}

	/**
	 * @return the set of unique ids
	 */
	public HashMap<String,Integer> getUniqueIDset() {
		return this.docid_index;
	}

}
